package com.foxzzz.array;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.foxzzz.base.GenUtil;

import java.util.List;

/**
 * @Author wujie
 * @Class Solution304
 * @Description
 * @Date 2021/3/2 9:55
 */
public class Solution304 {

    static class NumMatrix {
        int[][] sums;

        public NumMatrix(int[][] matrix) {
            int m = matrix.length;
            if (m > 0) {
                int n = matrix[0].length;
                sums = new int[m + 1][n + 1];
                for (int i = 0; i < m; i++) {
                    for (int j = 0; j < n; j++) {
                        sums[i + 1][j + 1] = sums[i][j + 1] + sums[i + 1][j] - sums[i][j] + matrix[i][j];
                    }
                }
            }
        }

        public int sumRegion(int row1, int col1, int row2, int col2) {
            return sums[row2 + 1][col2 + 1] - sums[row1][col2 + 1] - sums[row2 + 1][col1] + sums[row1][col1];
        }
    }


    public static int[][] toIntArray2D(String arrayStr) {
        JSONArray objects = JSON.parseArray(arrayStr);
        int height = objects.size();
        int weight = 0;
        if (height == 0) {
            return new int[0][0];
        } else {
            JSONArray objects1 = (JSONArray) objects.get(0);
            weight = objects1.size();
            if (weight == 0) {
                return new int[height][0];
            }
            int[][] res = new int[height][weight];
            for (int i = 0; i < objects.size(); i++) {
                JSONArray line = (JSONArray) objects.get(i);
                for (int j = 0; j < line.size(); j++) {
                    res[i][j] = (int) line.get(j);
                }
            }
            return res;
        }
    }

    public static void main(String[] args) {
        int[][] ints = toIntArray2D("[\n" +
                "  [3, 0, 1, 4, 2],\n" +
                "  [5, 6, 3, 2, 1],\n" +
                "  [1, 2, 0, 1, 5],\n" +
                "  [4, 1, 0, 1, 7],\n" +
                "  [1, 0, 3, 0, 5]\n" +
                "]\n");
        /**
         * 3, 3, 4, 8, 10
           8,14,18,24,27
         */
        NumMatrix numMatrix = new NumMatrix(ints);
        int i = numMatrix.sumRegion(2, 1, 4, 3);
        System.out.println(i);
    }
}
